const Koa = require('koa')
const serve = require('koa-static')
const path = require('path')
const fs = require('fs')
const Router = require('koa-router')
const render = require('koa-art-template')

const app = new Koa()
const router = new Router()

const config = {
  root: path.join(__dirname, 'static'),
  port: '80'
}
// 读取配置文件
const configPath = path.join(__dirname, './config.json')
if(fs.existsSync(configPath)) {
  const configJson = fs.readFileSync(configPath)
  if (configJson) {
    const customConfig = JSON.parse(configJson)
    if (customConfig.root) {
      config.root = customConfig.root
    }
    if (customConfig.port) {
      config.port = customConfig.port
    }
  }
}

// 判断文件夹是否存在，不存在则按路径顺序创建文件夹
if(!fs.existsSync(config.root)) {
  const pathList = config.root.split('/')
  try {
    let newPath = ''
    pathList.forEach(v => {
      if (v) {
        newPath = newPath + '/' + v
        if(!fs.existsSync(newPath)) {
          fs.mkdirSync(newPath)
        }
      }
    })
  } catch (error) {
    console.log(error)
  }
}

app.use(serve(config.root, {
  index: 'static-index' // 为了防止文件夹中有 index.html 自动渲染
}))

render(app, {
  root: path.join(__dirname, 'template'), // 视图的位置
  extname: '.html' // 后缀名
})

function pow1024(num) {
  return Math.pow(1024, num)
}
function filterSize(size) {
  if (!size) return ''
  if (size < pow1024(1)) return size + ' B'
  if (size < pow1024(2)) return (size / pow1024(1)).toFixed(0) + ' KB'
  if (size < pow1024(3)) return (size / pow1024(2)).toFixed(2) + ' MB'
  if (size < pow1024(4)) return (size / pow1024(3)).toFixed(2) + ' GB'
  return (size / pow1024(4)).toFixed(2) + ' TB'
}

router.get('/:sub*', async ctx => {
  try {
    const subPath = ctx.params.sub ? '/' + ctx.params.sub + '/' : '/'
    const files = fs.readdirSync(path.join(config.root, subPath))
    const filesInfo = files.map(v => {
      const stat = fs.statSync(path.join(config.root, subPath, v))
      const isDir = stat.isDirectory()
      return {
        path: v,
        isDir,
        size: filterSize(stat.size)
      }
    })
    const list = filesInfo.filter(v => v.isDir).concat(filesInfo.filter(v => !v.isDir))
    await ctx.render('index', {
      sub: subPath,
      list
    })
  } catch (error) {
    ctx.status = 404
    ctx.body = {
      msg: '找不到资源',
      path: ctx.method + ' ' + ctx.path
    }
  }
  
})

app.use(router.routes())

const os = require('os')
/**
 * 获取当前机器的ip地址
 */
function getIpAddress() {
  let ifaces = os.networkInterfaces()
  const ipv4s = []
  for (let dev in ifaces) {
    let iface = ifaces[dev]
    for (let i = 0; i < iface.length; i++) {
      let { family, address, internal } = iface[i]
      if (family === 'IPv4' && address !== '127.0.0.1' && !internal) {
        ipv4s.push(address + ':')
      }
    }
  }
  return ipv4s
}

app.listen(config.port, () => {
  const ipv4s = getIpAddress()
  ipv4s.forEach(v => {
    console.log('Static serve in: http://' + v + config.port)
  })
})